<?php
// Include database connection
require_once __DIR__ . '/../config/database.php';

// Create database connection
try {
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

// Include header
require_once 'includes/header.php';

// Get module filter
$module_id = isset($_GET['module']) ? (int)$_GET['module'] : 0;
$age_group = isset($_GET['age']) ? $_GET['age'] : '3-4';

// Handle actions
$message = '';
$message_type = '';

if (isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'update_item':
            $item_id = isset($_POST['item_id']) ? (int)$_POST['item_id'] : 0;
            $name = isset($_POST['name']) ? trim($_POST['name']) : '';
            $description = isset($_POST['description']) ? trim($_POST['description']) : '';
            $content = isset($_POST['content']) ? trim($_POST['content']) : '';
            $additional_info = isset($_POST['additional_info']) ? trim($_POST['additional_info']) : '';
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (empty($name) || empty($content)) {
                $message = '名称和内容不能为空';
                $message_type = 'danger';
            } else {
                try {
                    $sql = "UPDATE km_cognitive_items SET 
                            name = ?, description = ?, content = ?, 
                            additional_info = ?, is_active = ?, updated_at = NOW()
                            WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$name, $description, $content, $additional_info, $is_active, $item_id]);
                    
                    if ($stmt->rowCount() > 0) {
                        $message = '模块内容已成功更新';
                        $message_type = 'success';
                    } else {
                        $message = '没有内容被更新';
                        $message_type = 'warning';
                    }
                } catch (Exception $e) {
                    $message = '数据库错误: ' . $e->getMessage();
                    $message_type = 'danger';
                }
            }
            break;
            
        case 'add_item':
            $module_id = isset($_POST['module_id']) ? (int)$_POST['module_id'] : 0;
            $name = isset($_POST['name']) ? trim($_POST['name']) : '';
            $description = isset($_POST['description']) ? trim($_POST['description']) : '';
            $content = isset($_POST['content']) ? trim($_POST['content']) : '';
            $additional_info = isset($_POST['additional_info']) ? trim($_POST['additional_info']) : '';
            $image_path = isset($_POST['image_path']) ? trim($_POST['image_path']) : '';
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            if (empty($name) || empty($content) || empty($module_id)) {
                $message = '所有必填字段不能为空';
                $message_type = 'danger';
            } else {
                try {
                    // Get the max display order for this module
                    $sql = "SELECT MAX(display_order) as max_order FROM km_cognitive_items WHERE module_id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$module_id]);
                    
                    $row = $stmt->fetch(PDO::FETCH_ASSOC);
                    $display_order = ($row['max_order'] ?? 0) + 1;
                    
                    $sql = "INSERT INTO km_cognitive_items 
                            (module_id, name, description, content, additional_info, 
                            image_path, is_active, display_order, created_at, updated_at) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
                    $stmt = $conn->prepare($sql);
                    $stmt->execute([$module_id, $name, $description, $content, $additional_info, $image_path, $is_active, $display_order]);
                    
                    if ($stmt->rowCount() > 0) {
                        $message = '模块内容已成功添加';
                        $message_type = 'success';
                        
                        // Get the new item ID
                        $new_item_id = $conn->lastInsertId();
                        
                        // Create default image folder if needed
                        $module_slug = getModuleSlugById($conn, $module_id);
                        $item_folder = '../images/' . $module_slug;
                        if (!file_exists($item_folder) && !empty($module_slug)) {
                            mkdir($item_folder, 0755, true);
                        }
                    } else {
                        $message = '添加失败';
                        $message_type = 'danger';
                    }
                } catch (Exception $e) {
                    $message = '数据库错误: ' . $e->getMessage();
                    $message_type = 'danger';
                }
            }
            break;
            
        // Additional actions would be added here
    }
}

// Get all modules for dropdown
try {
    $sql = "SELECT m.id, m.name, c.age_group
            FROM km_cognitive_modules m
            JOIN km_cognitive_categories c ON m.category_id = c.id
            WHERE m.is_active = 1
            ORDER BY c.age_group, m.display_order";
    
    $stmt = $conn->query($sql);
    $all_modules = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $all_modules[] = $row;
    }
} catch (Exception $e) {
    $message = '数据库错误: ' . $e->getMessage();
    $message_type = 'danger';
}

// Get items for the selected module
$items = [];
$current_module = null;

if ($module_id > 0) {
    try {
        // Get current module info
        $sql = "SELECT m.id, m.name, m.slug, c.age_group
                FROM km_cognitive_modules m
                JOIN km_cognitive_categories c ON m.category_id = c.id
                WHERE m.id = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([$module_id]);
        
        
        if ($stmt->rowCount() > 0) {
            $current_module = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Get items for this module
            $sql = "SELECT i.id, i.name, i.description, i.content, i.additional_info,
                        i.image_path, i.is_active, i.display_order, i.updated_at,
                        (SELECT COUNT(*) FROM km_cognitive_item_images img WHERE img.item_id = i.id) as image_count
                    FROM km_cognitive_items i
                    WHERE i.module_id = ?
                    ORDER BY i.display_order ASC";
            
            $stmt = $conn->prepare($sql);
            $stmt->execute([$module_id]);
            
            
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $items[] = $row;
            }
        }
    } catch (Exception $e) {
        $message = '数据库错误: ' . $e->getMessage();
        $message_type = 'danger';
    }
}

// Helper function to get module slug by ID
function getModuleSlugById($conn, $module_id) {
    $sql = "SELECT slug FROM km_cognitive_modules WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$module_id]);
    
    
    if ($stmt->rowCount() > 0) {
        return $stmt->fetch(PDO::FETCH_ASSOC)['slug'];
    }
    
    return '';
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">模块内容管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <div class="btn-group me-2">
            <?php if ($module_id > 0): ?>
            <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addItemModal">
                <i class="bi bi-plus-lg"></i> 添加内容
            </button>
            <?php endif; ?>
            <a href="modules.php" class="btn btn-sm btn-outline-secondary">管理模块</a>
        </div>
    </div>
</div>

<?php if (!empty($message)): ?>
<div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show">
    <?php echo $message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">选择模块</h6>
    </div>
    <div class="card-body">
        <form method="get" class="mb-4">
            <div class="row g-3 align-items-center">
                <div class="col-md-6">
                    <select name="module" class="form-select" onchange="this.form.submit()">
                        <option value="">-- 请选择模块 --</option>
                        <?php foreach ($all_modules as $mod): ?>
                        <option value="<?php echo $mod['id']; ?>" <?php echo $mod['id'] == $module_id ? 'selected' : ''; ?>>
                            <?php echo $mod['age_group']; ?>岁 - <?php echo htmlspecialchars($mod['name']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </form>
        
        <?php if ($current_module): ?>
        <div class="alert alert-info">
            当前模块: <strong><?php echo htmlspecialchars($current_module['name']); ?></strong> 
            (<?php echo $current_module['age_group']; ?>岁)
        </div>
        <?php endif; ?>
        
        <?php if ($module_id > 0): ?>
        <div class="table-responsive">
            <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>描述</th>
                        <th>内容摘要</th>
                        <th>图片</th>
                        <th>状态</th>
                        <th>显示顺序</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($items)): ?>
                    <tr>
                        <td colspan="8" class="text-center">暂无数据</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($items as $item): ?>
                        <tr>
                            <td><?php echo $item['id']; ?></td>
                            <td><?php echo htmlspecialchars($item['name']); ?></td>
                            <td class="text-truncate" style="max-width: 150px;">
                                <?php echo htmlspecialchars($item['description']); ?>
                            </td>
                            <td class="text-truncate" style="max-width: 200px;">
                                <?php echo htmlspecialchars($item['content']); ?>
                            </td>
                            <td>
                                <?php if (!empty($item['image_path'])): ?>
                                <img src="<?php echo htmlspecialchars($item['image_path']); ?>" 
                                    alt="<?php echo htmlspecialchars($item['name']); ?>" 
                                    class="img-thumbnail" style="width: 50px; height: 50px;">
                                <?php endif; ?>
                                <span class="badge bg-info"><?php echo $item['image_count']; ?> 图片</span>
                            </td>
                            <td>
                                <span class="badge <?php echo $item['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                    <?php echo $item['is_active'] ? '启用' : '禁用'; ?>
                                </span>
                            </td>
                            <td><?php echo $item['display_order']; ?></td>
                            <td>
                                <button type="button" class="btn btn-sm btn-primary btn-edit-item" 
                                    data-id="<?php echo $item['id']; ?>"
                                    data-name="<?php echo htmlspecialchars($item['name']); ?>"
                                    data-description="<?php echo htmlspecialchars($item['description']); ?>"
                                    data-content="<?php echo htmlspecialchars($item['content']); ?>"
                                    data-additional-info="<?php echo htmlspecialchars($item['additional_info']); ?>"
                                    data-active="<?php echo $item['is_active']; ?>"
                                    data-bs-toggle="modal" data-bs-target="#editItemModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <a href="images.php?item=<?php echo $item['id']; ?>" class="btn btn-sm btn-info">
                                    <i class="bi bi-images"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <?php elseif (empty($module_id)): ?>
        <div class="alert alert-warning">
            请从上方下拉菜单选择一个模块以查看和管理其内容。
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Edit Item Modal -->
<div class="modal fade" id="editItemModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="action" value="update_item">
                <input type="hidden" name="item_id" id="edit_item_id">
                
                <div class="modal-header">
                    <h5 class="modal-title">编辑模块内容</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_name" class="form-label">名称</label>
                        <input type="text" class="form-control" id="edit_name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_content" class="form-label">内容</label>
                        <textarea class="form-control" id="edit_content" name="content" rows="3" required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_additional_info" class="form-label">附加信息</label>
                        <textarea class="form-control" id="edit_additional_info" name="additional_info" rows="4" placeholder="使用分号分隔不同的点"></textarea>
                        <div class="form-text">每个点使用分号(;)分隔，例如: "含有丰富的营养;可以是叶子、根、茎或果实;有各种口味和质地"</div>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active">
                        <label class="form-check-label" for="edit_is_active">
                            启用
                        </label>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存更改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Item Modal -->
<?php if ($module_id > 0): ?>
<div class="modal fade" id="addItemModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" name="action" value="add_item">
                <input type="hidden" name="module_id" value="<?php echo $module_id; ?>">
                
                <div class="modal-header">
                    <h5 class="modal-title">添加模块内容</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="add_name" class="form-label">名称</label>
                        <input type="text" class="form-control" id="add_name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="add_description" class="form-label">描述</label>
                        <textarea class="form-control" id="add_description" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="add_content" class="form-label">内容</label>
                        <textarea class="form-control" id="add_content" name="content" rows="3" required></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="add_additional_info" class="form-label">附加信息</label>
                        <textarea class="form-control" id="add_additional_info" name="additional_info" rows="4" placeholder="使用分号分隔不同的点"></textarea>
                        <div class="form-text">每个点使用分号(;)分隔，例如: "含有丰富的营养;可以是叶子、根、茎或果实;有各种口味和质地"</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="add_image_path" class="form-label">基础图片路径</label>
                        <input type="text" class="form-control" id="add_image_path" name="image_path" value="images/<?php echo htmlspecialchars($current_module['slug']); ?>/<?php echo strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $current_module['slug'])); ?>-1.jpg">
                        <div class="form-text">图片路径将在图片管理中进一步完善</div>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" id="add_is_active" name="is_active" checked>
                        <label class="form-check-label" for="add_is_active">
                            启用
                        </label>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
$(document).ready(function() {
    // Edit item modal
    $('.btn-edit-item').on('click', function() {
        var id = $(this).data('id');
        var name = $(this).data('name');
        var description = $(this).data('description');
        var content = $(this).data('content');
        var additionalInfo = $(this).data('additional-info');
        var active = $(this).data('active');
        
        $('#edit_item_id').val(id);
        $('#edit_name').val(name);
        $('#edit_description').val(description);
        $('#edit_content').val(content);
        $('#edit_additional_info').val(additionalInfo);
        $('#edit_is_active').prop('checked', active == 1);
    });
});
</script>

<?php
// Include footer
require_once 'includes/footer.php';
?> 